package controllers

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/utils"
	"commerce/vo"
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
)

func init() {

	common.Templates["sku"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/sku.html")))
	common.Templates["sku_edit"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/sku_edit.html")))
}

func ListSku(w http.ResponseWriter, r *http.Request) {

	var goodsId = 0
	goodsIdStr := r.FormValue("goodsId")
	if len(goodsIdStr) > 0 {
		goodsId, _ = strconv.Atoi(goodsIdStr)
	}
	pageNo, err := strconv.Atoi(r.FormValue("pageNo"))
	if err != nil {
		pageNo = 1
	}
	pageSize, err := strconv.Atoi(r.FormValue("pageSize"))
	if err != nil {
		pageSize = common.PAGE_SIZE
	}
	name := strings.TrimSpace(r.FormValue("name"))

	var page, _ = data.ListSku(goodsId, pageNo, pageSize, name)
	if page == nil {
		common.Templates["5xx"].Execute(w, nil)
		return
	}
	// 分页条件查询使用
	var qs = r.URL.RawQuery

	index := strings.Index(r.RequestURI, "&pageNo=")
	var flag bool
	// 这一步操作是点击分页来的
	if index != -1 {
		qs = r.RequestURI[:index]
		flag = true
	} else {
		// 首次点击搜索按钮查询
		flag = false
		qs = "?"
		if len(name) > 0 {
			qs += "name=" + name
		}
	}
	if flag {
		page.Url = qs
	} else {
		page.Url = r.RequestURI + qs
	}
	common.Templates["sku"].Execute(w, page)
}

func AddSkuUIHandler(w http.ResponseWriter, r *http.Request) {

	var k model.Sku
	allGoods, _ := data.ListAllGoodsIdName()
	// 查询所有商品id-name
	k.AllGoods = allGoods

	common.Templates["sku_edit"].Execute(w, k)
}

func GetSkuHandler(w http.ResponseWriter, r *http.Request) {

	skuId, _ := strconv.Atoi(r.FormValue("id"))
	k, err := data.GetSkuById(skuId)
	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		return
	}
	// 查指定goodsId的销售属性
	skuAttrValueList, err := data.ListSkuAttrValueByGoodsId(k.GoodsId)
	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		return
	}
	k.SkuAttrValues = skuAttrValueList
	allGoods, _ := data.ListAllGoodsIdName()
	// 查询所有商品id-name
	k.AllGoods = allGoods

	// 查sku销售属性
	skuSaleAttrs, _ := data.ListSkuAttrValueBySkuId(skuId, true)
	k.OwnSaleAttrValues = skuSaleAttrs

	common.Templates["sku_edit"].Execute(w, k)
}

// ajax请求

func ListSkuAttrValueByGoodsId(w http.ResponseWriter, r *http.Request) {

	goodsId, _ := strconv.Atoi(r.FormValue("goodsId"))
	if goodsId == 0 {
		w.WriteHeader(http.StatusOK)
		return
	}
	// 查指定goodsId的销售属性
	skuAttrValueList, err := data.ListSkuAttrValueByGoodsId(goodsId)
	if err != nil {
		common.DisplayAppErr(w, err, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")

	j, err := json.Marshal(vo.Ok(skuAttrValueList))
	if err != nil {
		common.DisplayAppErr(w, err, "序列化响应信息失败", http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}

func AddOrEditSkuHandler(w http.ResponseWriter, r *http.Request) {

	var id = 0
	idVal := r.PostFormValue("id")
	if len(idVal) > 0 {
		id, _ = strconv.Atoi(idVal)
	}
	skuName := r.PostFormValue("skuName")
	description := r.PostFormValue("description")
	// 处理sku销售属性
	skuAttrValue := r.PostForm["skuAttrValue"]

	var skuAttrIds []int
	for _, v := range skuAttrValue {
		id, _ := strconv.Atoi(strings.Split(v, "_")[0])
		skuAttrIds = append(skuAttrIds, id)
	}
	goodsAttrs, err := data.ListGoodsAttrById(skuAttrIds)

	if len(goodsAttrs) <= 0 {
		common.Templates["5xx"].Execute(w, fmt.Sprintf("%s-%s", "商品sku属性输入有误！", skuAttrValue))
		return
	}
	price, _ := strconv.ParseFloat(r.PostFormValue("price"), 64)
	realPrice, _ := strconv.ParseFloat(r.PostFormValue("realPrice"), 64)
	priority, _ := strconv.Atoi(r.PostFormValue("priority"))
	goodsId, _ := strconv.Atoi(r.PostFormValue("goodsId"))
	var mainImg = ""
	f, header, err := r.FormFile("mainImg")
	// 用户上传了主图
	if err == nil && f != nil {
		uploadedPath, err := utils.Upload(f, header.Filename)
		if err != nil {
			common.Error.Printf("upload sku main img failed, filename:%s, err:%v", header.Filename, err)
		} else {
			mainImg = uploadedPath
			// 更新操作
			if id > 0 {
				// 删除老的图片(如果有)
				kp, _ := data.GetSkuById(id)
				if kp != nil && len(kp.MainImg) > 0 {
					fns := strings.LastIndex(kp.MainImg, "/")
					if fns > -1 {
						utils.Delete(kp.MainImg[fns+1:])
					}
				}
			}
		}
	}
	k := model.Sku{Id: id, Name: skuName, Description: description, Price: price, RealPrice: realPrice,
		Priority: priority, GoodsId: goodsId, MainImg: mainImg}
	if id <= 0 {
		id, err = data.AddSku(context.Background(), k, skuAttrValue, goodsAttrs)
	} else {
		id, err = data.UpdateSku(context.Background(), k, skuAttrValue, goodsAttrs)
	}
	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/sku/list", http.StatusFound)
}

func OnSaleSkuHandler(w http.ResponseWriter, r *http.Request) {

	updateSkuStatusHandler(w, r, 1)
}

func OffSaleSkuHandler(w http.ResponseWriter, r *http.Request) {

	updateSkuStatusHandler(w, r, 0)
}

func updateSkuStatusHandler(w http.ResponseWriter, r *http.Request, status int) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	data.UpdateSkuStatus(id, status)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
}

func UpdateHotStatus(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	hotStatus, err := strconv.Atoi(r.FormValue("hotStatus"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	data.UpdateSkuHotStatus(id, hotStatus)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
}
